import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { VisitingAppointmentQuery, getVisitingAppointmentListApi } from "@/api/visiting/appointment";
import { addDialog } from "@/components/ReDialog";
import { ElMessageBox, Sort } from "element-plus";
import { AddVisitRequest } from "../utils/types";
import { type PaginationProps } from "@pureadmin/table";
import {
  addVisitingAppointmentApi,
  updateVisitingAppointmentApi,
  deleteVisitingAppointmentApi,
  VisitingAppointmentRequest,
  checkVisitingAppointmentApi
} from "@/api/visiting/appointment";
import { reactive, ref, onMounted, h, toRaw } from "vue";
import { useUserStoreHook } from "@/store/modules/user";
import { CommonUtils } from "@/utils/common";

export function useVisitHook() {
  const defaultSort: Sort = {
    prop: "createTime",
    order: "descending"
  };

  const pagination: PaginationProps = {
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  };

  const searchFormParams = reactive<VisitingAppointmentQuery>({
	status: undefined,
    orderColumn: defaultSort.prop,
    orderDirection: defaultSort.order
  });

  // TODO  ******困惑的问题*******
  // const pagination = reactive<PaginationProps>({
  //   total: 0,
  //   pageSize: 10,
  //   currentPage: 1,
  //   background: true
  // });
  // TODO 使用watchEffect会导致 axios请求拦截器中的参数使用的是旧值
  // watchEffect(() => {
  //   searchFormParams.pageNum = pagination.currentPage;
  //   searchFormParams.pageSize = pagination.pageSize;
  // });

  const formRef = ref();
  const dataList = ref([]);
  const pageLoading = ref(true);
  const multipleSelection = ref([]);

  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left"
    },
    {
      label: "来访日期",
      prop: "lfTime",
      // formatter: ({ lfTime }) => dayjs(lfTime).format("YYYY-MM-DD HH:mm"),
      minWidth: 200,
	  cellRenderer: ({ row, props }) => (
	    <span>
	      {dayjs(row.lfTime).format("MM-DD HH:mm")} 至 {dayjs(row.visitTimeEnd).format("MM-DD HH:mm")}
	    </span>
	  )
    },
    {
      label: "申请人",
      prop: "userName",
      minWidth: 100
    },
    {
      label: "申请人电话",
      prop: "userPhone",
      minWidth: 120
    },
    {
      label: "拜访部门",
      prop: "bfDeptName",
      minWidth: 100
    },
    {
      label: "拜访人",
      prop: "bfUserName",
      minWidth: 100
    },
    {
      label: "来访人数",
      prop: "lfRs",
      minWidth: 80
    },
    {
      label: "来访事由",
      prop: "lfSy",
      minWidth: 200
    },
    {
      label: "审核状态",
      prop: "status",
      minWidth: 118,
	  fixed: 'right',
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.status == 0 ? null : row.status == 1 ? 'warning' : row.status == 2 ? 'danger' : 'success'}
          effect="plain"
        >
          {row.status == 0 ? '待审批' : row.status == 1 ? '已审批待来访' : row.status == 2 ? '审批未通过' : '已来访'}
        </el-tag>
      )
    },
    {
      label: "车牌",
      prop: "fkCl",
      minWidth: 120
    },
    {
      label: "人脸",
      prop: "fkRl",
      minWidth: 130,
	  cellRenderer: ({ row, props }) => {
		  return row.fkRl ? <el-image
		  style="width: 100px; height: 100px;vertical-align: top;"
		  src={row.fkRl}
		  zoom-rate={1.2}
		  max-scale={7}
		  min-scale={0.2}
		  preview-src-list={[row.fkRl]}
		  fit="cover"
		  preview-teleported
		  lazy
		  hide-on-click-modal
		/> : '-'
	  }
    },
	{
	  label: "相关图片",
	  prop: "xgTp",
	  minWidth: 130,
	  cellRenderer: ({ row, props }) => {
		  let url = row.xgTp ? row.xgTp.split(',') : [];
		  return row.xgTp ? <el-image
		  style="width: 100px; height: 100px;vertical-align: top;"
		  src={url[0]}
		  zoom-rate={1.2}
		  max-scale={7}
		  min-scale={0.2}
		  preview-src-list={url}
		  fit="cover"
		  preview-teleported
		  lazy
		  hide-on-click-modal
		/> : '-'
	  }
	},
	{
	  label: "其他补充",
	  prop: "qtBc",
	  minWidth: 120
	},
    // {
    //   label: "创建者",
    //   prop: "creatorName",
    //   minWidth: 120
    // },
    {
      label: "创建时间",
      minWidth: 180,
      prop: "createTime",
      sortable: "custom",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 240,
      slot: "operation"
    }
  ];

  function onSearch() {
    // 点击搜索的时候 需要重置分页
    pagination.currentPage = 1;

    getVisitList();
  }

  function resetForm(formEl, tableRef) {
    if (!formEl) return;
    // 清空查询参数
    formEl.resetFields();
    // 清空排序
    searchFormParams.orderColumn = undefined;
    searchFormParams.orderDirection = undefined;
    tableRef.getTableRef().clearSort();
    // 重置分页并查询
    onSearch();
  }

  async function getVisitList(sort: Sort = defaultSort) {
    if (sort != null) {
      CommonUtils.fillSortParams(searchFormParams, sort);
    }
    CommonUtils.fillPaginationParams(searchFormParams, pagination);

    pageLoading.value = true;
    const { data } = await getVisitingAppointmentListApi(
      toRaw(searchFormParams)
    ).finally(() => {
      pageLoading.value = false;
    });

    dataList.value = data.rows;
    pagination.total = data.total;
  }

  async function handleDelete(row) {
    await deleteVisitingAppointmentApi([row.id]).then(() => {
      message(`您删除了申请人为${row.userName}的这条数据`, { type: "success" });
      // 刷新列表
      getVisitList();
    });
  }

  async function handleBulkDelete(tableRef) {
    if (multipleSelection.value.length === 0) {
      message("请选择需要删除的数据", { type: "warning" });
      return;
    }

    ElMessageBox.confirm(
      `确认要<strong>删除</strong>编号为<strong style='color:var(--el-color-primary)'>[ ${multipleSelection.value} ]</strong>的通知吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        await deleteVisitingAppointmentApi(multipleSelection.value).then(() => {
          message(`您删除了申请编号为[ ${multipleSelection.value} ]的数据`, {
            type: "success"
          });
          // 刷新列表
          getVisitList();
        });
      })
      .catch(() => {
        message("取消删除", {
          type: "info"
        });
        // 清空checkbox选择的数据
        tableRef.getTableRef().clearSelection();
      });
  }

  async function handleAdd(row, done) {
    await addVisitingAppointmentApi(row as VisitingAppointmentRequest).then(() => {
      message(`您新增了申请人为${row.userName}的这条数据`, {
        type: "success"
      });
      // 关闭弹框
      done();
      // 刷新列表
      getVisitList();
    });
  }

  async function handleUpdate(row, done) {
    await updateVisitingAppointmentApi(row as VisitingAppointmentRequest).then(() => {
      message(`您更新了申请人为${row.userName}的这条数据`, {
        type: "success"
      });
      // 关闭弹框
      done();
      // 刷新列表
      getVisitList();
    });
  }

  function openDialog(title = "新增", row?: AddVisitRequest) {
	  const lfDateRange = [row?.lfTime, row?.visitTimeEnd]
    addDialog({
      title: `${title}申请`,
      props: {
        formInline: {
          lfTime: row?.lfTime ?? "",
		  visitTimeEnd: row?.visitTimeEnd ?? "",
          userName: row?.userName ?? "",
          userPhone: row?.userPhone ?? "",
          bfDept: row?.bfDept ?? "",
          bfUserName: row?.bfUserName ?? "",
          lfRs: row?.lfRs ?? 0,
          lfSy: row?.lfSy ?? "",
          status: row?.status ?? "",
          fkCl: row?.fkCl ?? "",
          fkRl: row?.fkRl ?? "",
          xgTp: row?.xgTp ?? "",
          qtBc: row?.qtBc ?? "",
		  
		  lfDateRange
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const formRuleRef = formRef.value.getFormRuleRef();

        const curData = options.props.formInline as AddVisitRequest;

        formRuleRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
			const { lfDateRange, ...more } = curData;
            // 表单规则校验通过
            if (title === "新增") {
              handleAdd({
				  ...more,
				  lfTime: lfDateRange[0],
				  visitTimeEnd: lfDateRange[1],
			  }, done);
            } else {
              more.id = row.id;
              handleUpdate({
				  ...more,
				  lfTime: lfDateRange[0],
				  visitTimeEnd: lfDateRange[1],
			  }, done);
            }
          }
        });
      }
    });
  }

  async function approveUpdate(row: any, status) {
	  await checkVisitingAppointmentApi({
		  id: row.id,
		  status: status,
		  spJg: status == 0 ? '设置为待审批' : status == 1 ? '审批通过，等待您的来访！' : status == 2 ? '抱歉，您的申请未通过审批！' : '欢迎您的来访！'
	  }).then(() => {
	    message(`已变更状态为${status == 0 ? '待审批' : status == 1 ? '已审批待来访' : status == 2 ? '未通过' : '已来访'}`, {
	      type: "success"
	    });
	    // 刷新列表
	    getVisitList();
	  });
  }

  onMounted(() => {
    getVisitList();
  });

  return {
    searchFormParams,
    pageLoading,
    columns,
    dataList,
    pagination,
    defaultSort,
    multipleSelection,
    getVisitList,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleBulkDelete,
	approveUpdate
  };
}
